import datetime
from typing import List, Dict

from sqlalchemy import Column, String, Index, Integer, Text
from sqlalchemy.orm import Session

from common.database import Base
from common.database import SessionMixin


class ExpenseQuotaUserInfo(Base, SessionMixin):
    """
    公司用户企业微信信息
    """
    __tablename__ = "expense_quota_user_info"

    username = Column(String(150), nullable=False, comment="姓名")
    name = Column(String(150), nullable=False, comment="名称")
    department = Column(String(150), nullable=True, comment="部门")
    department_wechat_id = Column(String(150), nullable=True, comment="所属部门企业微信ID")
    mobile = Column(String(150), nullable=True, comment="手机号码")
    email = Column(String(150), nullable=True, comment="公司邮箱")
    created_at = Column(String(150), nullable=True, comment="创建时间")
    updated_at = Column(String(150), nullable=True, comment="修改时间")

    __table_args__ = (
        Index('idx_expense_quota_user_info_uuid', 'uuid', unique=True),
        Index('idx_expense_quota_user_info_username', 'username', unique=True),
        {
            'mysql_engine': 'innodb',
            'mysql_charset': 'utf8mb4',
            'mysql_collate': 'utf8mb4_unicode_ci',
            'extend_existing': True,
            'mysql_row_format': 'dynamic',
        }
    )

    def __repr__(self):
        return f"<uuid='{self.uuid}',username='{self.username}'>"

    @classmethod
    def get_department_by_username(cls, db: Session, username):
        return db.query(cls).with_entities(cls.department).filter(cls.username == username).to_dict_first()


class ExpenseQuota(Base, SessionMixin):
    """
    费用配额
    """
    __tablename__ = "expense_quota"
    work_order_id = Column(Integer, nullable=True, comment="工单ID")
    title = Column(String(150), nullable=True, comment="申请标题")
    creator = Column(String(150), nullable=False, comment="申请人")
    price_month = Column(String(150), nullable=False, comment="月度费用")
    type = Column(String(150), nullable=True, comment="费用类型")
    cost_ownership = Column(String(150), nullable=True, comment="费用归属")
    cost_create_year = Column(String(150), nullable=True, comment="费用创建年份")
    cost_create_month = Column(String(150), nullable=True, comment="费用创建月份")
    remarks = Column(String(150), nullable=True, comment="备注")

    __table_args__ = (
        Index('idx_expense_quota_uuid', 'uuid', unique=True),
        Index('idx_expense_quota_cost_ownership', 'cost_ownership'),
        Index('idx_expense_quota_cost_create_datetime', 'cost_create_year', 'cost_create_month'),
        {
            'mysql_engine': 'innodb',
            'mysql_charset': 'utf8mb4',
            'mysql_collate': 'utf8mb4_unicode_ci',
            'extend_existing': True,
            'mysql_row_format': 'dynamic',
        }
    )

    def __repr__(self):
        return f"<uuid='{self.uuid}',creator='{self.creator}'>"

    @classmethod
    def get_quota_by_create_month(cls, db: Session, create_month):
        return db.query(cls).with_entities(cls.title, cls.cost_ownership, cls.price_month, cls.type,
                                           cls.cost_create_month).filter(
            cls.cost_create_month == create_month).order_by(cls.cost_create_month.asc()).to_dict()

    @classmethod
    def get_quota(cls, db: Session):
        return db.query(cls).with_entities(cls.work_order_id, cls.title, cls.cost_ownership, cls.cost_create_month,
                                           cls.type, cls.price_month).to_dict()


class ExpenseQuotaDepartmentBudget(Base, SessionMixin):
    """
    部分资源配额管理
    """
    __tablename__ = "expense_quota_department_budget"
    department = Column(String(150), nullable=True, comment="部门")
    budget_month = Column(String(150), nullable=True, comment="月预算")
    budget_year = Column(String(150), nullable=True, comment="年预算")
    remarks = Column(Text, nullable=True, comment="备注")

    __table_args__ = (
        Index('idx_expense_quota_department__budget_uuid', 'uuid', unique=True),
        Index('idx_expense_quota_department_budget_department', 'department', unique=True),
        {
            'mysql_engine': 'innodb',
            'mysql_charset': 'utf8mb4',
            'mysql_collate': 'utf8mb4_unicode_ci',
            'extend_existing': True,
            'mysql_row_format': 'dynamic',
        }
    )

    def __repr__(self):
        return f"<uuid='{self.uuid}',department='{self.department}'>"


class ContainerQuota(Base, SessionMixin):
    """
    容器配额管理
    """
    __tablename__ = "container_quota"
    work_order_id = Column(Integer, nullable=True, comment="工单ID")
    title = Column(String(150), nullable=True, comment="申请标题")
    type = Column(String(150), nullable=True, comment="类型")
    creator = Column(String(150), nullable=False, comment="申请人")
    resource_cpu = Column(String(150), nullable=True, comment="资源cpu")
    resource_mem = Column(String(150), nullable=True, comment="资源mem")
    resource_ownership = Column(String(150), nullable=True, comment="资源归属")
    create_year = Column(String(150), nullable=True, comment="创建年份")
    create_month = Column(String(150), nullable=True, comment="创建月份")
    remarks = Column(String(150), nullable=True, comment="备注")

    __table_args__ = (
        Index('idx_container_quota_uuid', 'uuid', unique=True),
        Index('idx_container_quota_resource_ownership', 'resource_ownership'),
        Index('idx_container_quota_create_datetime', 'create_year', 'create_month'),
        {
            'mysql_engine': 'innodb',
            'mysql_charset': 'utf8mb4',
            'mysql_collate': 'utf8mb4_unicode_ci',
            'extend_existing': True,
            'mysql_row_format': 'dynamic',
        }
    )

    def __repr__(self):
        return f"<uuid='{self.uuid}',creator='{self.creator}'>"


class ContainerQuotaDepartmentBudget(Base, SessionMixin):
    """
    容器配额
    """
    __tablename__ = "container_quota_department_budget"
    department = Column(String(150), nullable=True, comment="部门")
    budget_cpu_month = Column(String(150), nullable=True, comment="预算资源cpu月")
    budget_mem_month = Column(String(150), nullable=True, comment="预算资源mem月")
    budget_cpu_year = Column(String(150), nullable=True, comment="预算资源cpu年")
    budget_mem_year = Column(String(150), nullable=True, comment="预算资源mem年")
    remarks = Column(Text, nullable=True, comment="备注")

    __table_args__ = (
        Index('idx_container_quota_department_budget_uuid', 'uuid', unique=True),
        {
            'mysql_engine': 'innodb',
            'mysql_charset': 'utf8mb4',
            'mysql_collate': 'utf8mb4_unicode_ci',
            'extend_existing': True,
            'mysql_row_format': 'dynamic',
        }
    )

    def __repr__(self):
        return f"<uuid='{self.uuid}',creator='{self.creator}'>"

    #
    # @classmethod
    # def get_by_uuid(cls, db: Session, uuid: int) -> Dict:
    #     return db.query(cls).filter(cls.uuid == uuid).to_dict_first()
    #
    # @classmethod
    # def get_by_username(cls, db: Session, username: str) -> Dict:
    #     return db.query(cls).filter(cls.username == username).to_dict_first()
    #
    # @classmethod
    # def get_roles_by_uuid(cls, db: Session, uuid: int) -> List[Dict]:
    #     return db.query(AuthRoles).with_entities(AuthRoles.uuid, AuthRoles.description).outerjoin(
    #         AuthUsersRoles).outerjoin(cls).filter(cls.uuid == uuid).to_dict()
    #
    # @classmethod
    # def get_permissions_tags_by_uuid(cls, db: Session, uuid: int) -> List[List]:
    #     items = db.query(AuthPermissions).with_entities(distinct(AuthPermissions.tags).label("tag")).join(
    #         AuthRolesPermissions).join(AuthRoles).join(AuthUsersRoles).join(cls).filter(cls.uuid == uuid).all()
    #     return [cls.to_list(item) for item in items if item]
    #
    # @classmethod
    # def get_permissions_by_uuid(cls, db: Session, uuid: int) -> List[Dict]:
    #     return db.query(AuthPermissions).with_entities(AuthPermissions.url, AuthPermissions.method).join(
    #         AuthRolesPermissions).join(AuthRoles).join(AuthUsersRoles).join(cls).filter(cls.uuid == uuid).to_dict()
    #
    # @classmethod
    # def get_user_roles_paginate(cls, db: Session, page, per_page) -> List[Dict]:
    #     data = cls.get_paginate(db, page, per_page)
    #     for item in data.get('items'):
    #         user = db.query(cls).filter(cls.uuid == item.get('uuid')).first()
    #         if user.auth_roles:
    #             item.update({'user_roles': sorted(
    #                 user.auth_roles.with_entities(AuthRoles.uuid, AuthRoles.description).to_dict(),
    #                 key=lambda s: s.get('uuid'), reverse=False)})
    #         else:
    #             item.update({'user_roles': []})
    #     return data


# class AuthRoles(Base, SessionMixin):
#     """
#     基于角色权限控制-角色表
#     """
#     __tablename__ = "auth_roles"
#     role_name = Column(String(168), nullable=False, comment='角色名称')
#     description = Column(String(168), nullable=False, comment='角色描述')
#     auth_users = relationship('AuthUsers', secondary=AuthUsersRoles, back_populates='auth_roles', lazy='dynamic')
#     auth_permissions = relationship('AuthPermissions', secondary=AuthRolesPermissions,
#                                     back_populates='auth_roles', lazy='dynamic')
#     create_time = Column(DateTime, default=datetime.datetime.now, nullable=False, comment="创建时间")
#     update_time = Column(DateTime, default=datetime.datetime.now, onupdate=datetime.datetime.now, nullable=False,
#                          comment="更新时间")
#
#     __table_args__ = (
#         Index('idx_auth_roles_uuid', 'uuid', unique=True),
#         Index('idx_auth_roles_name', 'role_name', unique=True),
#         Index('idx_auth_roles_uuid_description', 'uuid', 'description', unique=True),
#         {
#             'mysql_engine': 'innodb',
#             'mysql_charset': 'utf8mb4',
#             'mysql_collate': 'utf8mb4_unicode_ci',
#             'extend_existing': True,
#             'mysql_row_format': 'dynamic',
#         }
#     )
#
#     def __repr__(self):
#         return "<uuid='{}',role_name='{}'>".format(self.uuid, self.role_name)
#
#     @classmethod
#     def get_by_role_name(cls, db: Session, role_name: str) -> Dict:
#         return db.query(cls).filter(cls.role_name == role_name).to_dict_first()
#
#     @classmethod
#     def get_by_uuid(cls, db: Session, uuid: str) -> Dict:
#         return db.query(cls).filter(cls.uuid == uuid).to_dict_first()
#
#     @classmethod
#     def get_paginate(cls, db: Session, page, per_page):
#         return db.query(cls).with_entities(cls.uuid, cls.role_name, cls.description).paginate(page=page,
#                                                                                               per_page=per_page)
#
#     @classmethod
#     def get_role_permissions_paginate(cls, db: Session, page, per_page) -> List[Dict]:
#         data = cls.get_paginate(db, page, per_page)
#         for item in data.get('items'):
#             role = db.query(cls).filter(cls.uuid == item.get('uuid')).first()
#             if role.auth_permissions:
#                 item.update({'role_permissions': sorted(
#                     role.auth_permissions.with_entities(AuthPermissions.uuid, AuthPermissions.description).to_dict(),
#                     key=lambda s: s.get('uuid'), reverse=False)})
#             else:
#                 item.update({'role_permissions': []})
#         return data
#
#
# class AuthPermissions(Base, SessionMixin):
#     """
#     基于角色权限控制-权限表
#     """
#     __tablename__ = "auth_permissions"
#     permission_name = Column(String(40), nullable=False, comment='权限名称')
#     method = Column(String(8), nullable=True, comment='路由方式')
#     url = Column(String(40), nullable=True, comment='路由地址')
#     tags = Column(String(40), nullable=True, comment='路由标签')
#     summary = Column(String(40), nullable=True, comment='概要说明')
#     description = Column(String(40), nullable=True, comment='权限描述')
#     auth_roles = relationship('AuthRoles', secondary=AuthRolesPermissions, back_populates='auth_permissions',
#                               lazy='dynamic')
#     create_time = Column(DateTime, default=datetime.datetime.now, nullable=False, comment="创建时间")
#     update_time = Column(DateTime, default=datetime.datetime.now, onupdate=datetime.datetime.now, nullable=False,
#                          comment="更新时间")
#
#     __table_args__ = (
#         Index('idx_auth_permissions_uuid', 'uuid', unique=True),
#         Index('idx_auth_permissions_name', 'permission_name', unique=True),
#         {
#             'mysql_engine': 'innodb',
#             'mysql_charset': 'utf8mb4',
#             'mysql_collate': 'utf8mb4_unicode_ci',
#             'extend_existing': True,
#             'mysql_row_format': 'dynamic',
#         }
#     )
#
#     def __repr__(self):
#         return "<uuid='{}',permission_name='{}'>".format(self.uuid, self.permission_name)
#
#     @classmethod
#     def get_by_uuid(cls, db: Session, uuid: str) -> Dict:
#         return db.query(cls).filter(cls.uuid == uuid).to_dict()
#
#     @classmethod
#     def get_paginate(cls, db: Session, page, per_page):
#         return db.query(cls).with_entities(cls.uuid, cls.tags, cls.method, cls.url, cls.summary,
#                                            cls.description).paginate(page=page, per_page=per_page)


if __name__ == "__main__":
    # departments = [
    #     {"id": 65, "department": "技术研发中心-个人业务平台-业务前端"},
    #     {"id": 74, "department": "技术研发中心-个人业务平台-业务后台"},
    #     {"id": 40, "department": "技术研发中心-个人业务平台-管理系统"},
    #     # {"id": 15, "department": "技术研发中心-个人业务平台-技术架构"},
    #     {"id": 67, "department": "技术研发中心-天冕科技-云平台"},
    #     {"id": 73, "department": "技术研发中心-天冕科技-数据平台"},
    #     {"id": 41, "department": "技术研发中心-天冕科技-数据智能"},
    #     {"id": 39, "department": "技术研发中心-天冕科技-人工智能"},
    #     {"id": 72, "department": "技术研发中心-系统运维-运维"},
    #     {"id": 79, "department": "技术研发中心-系统运维-数据库"},
    #     {"id": 25, "department": "总裁办-商业智能"},
    #     {"id": 78, "department": "总裁办-信息安全"},
    # ]
    #
    # from common.database import SessionLocal
    # from app.expense_quota.utils import welab_users
    # from pprint import pprint
    #
    # session = SessionLocal()
    # data = []
    # for item in departments:
    #     if item.get("id"):
    #         for user in welab_users(item.get("id")).get("data").get("list"):
    #             if user.get("username"):
    #                 data.append({"username": user.get("username"), "name": user.get("name"),
    #                              "department_wechat_id": item.get("id"), "department": item.get("department"),
    #                              "mobile": user.get("mobile"), "email": user.get("email"),
    #                              "created_at": user.get("created_at"), "updated_at": user.get("updated_at")})
    #
    # session.close()
    # pprint(data)

    # budget = [
    #     {"department": "技术研发中心-个人业务平台-业务前端", "budget_cpu_month": "2000", "budget_year": "24000"},
    #     {"department": "技术研发中心-个人业务平台-业务后台", "budget_cpu_month": "2000", "budget_year": "24000"},
    #     {"department": "技术研发中心-个人业务平台-管理系统", "budget_cpu_month": "2000", "budget_year": "24000"},
    #     {"department": "技术研发中心-个人业务平台-技术架构", "budget_cpu_month": "2000", "budget_year": "24000"},
    #     {"department": "技术研发中心-天冕科技-云平台", "budget_cpu_month": "2000", "budget_year": "24000"},
    #     {"department": "技术研发中心-天冕科技-数据平台", "budget_cpu_month": "2000", "budget_year": "24000"},
    #     {"department": "技术研发中心-天冕科技-数据智能", "budget_cpu_month": "2000", "budget_year": "24000"},
    #     {"department": "技术研发中心-天冕科技-人工智能", "budget_cpu_month": "2000", "budget_year": "24000"},
    #     {"department": "技术研发中心-系统运维-运维", "budget_cpu_month": "2000", "budget_year": "24000"},
    #     {"department": "技术研发中心-系统运维-数据库", "budget_cpu_month": "2000", "budget_year": "24000"},
    # ]
    #
    # from common.database import SessionLocal
    # session = SessionLocal()
    # ExpenseQuotaDepartmentBudget.saves(session, budget)
    # session.close()

    container_budget = [
        {"department": "技术研发中心-个人业务平台-业务前端", "budget_cpu_month": "10000", "budget_mem_month": "30720",
         "budget_cpu_year": "120000", "budget_mem_year": "368640"},
        {"department": "技术研发中心-个人业务平台-业务后台", "budget_cpu_month": "10000", "budget_mem_month": "30720",
         "budget_cpu_year": "120000", "budget_mem_year": "368640"},
        {"department": "技术研发中心-个人业务平台-管理系统", "budget_cpu_month": "10000", "budget_mem_month": "30720",
         "budget_cpu_year": "120000", "budget_mem_year": "368640"},
        {"department": "技术研发中心-个人业务平台-技术架构", "budget_cpu_month": "10000", "budget_mem_month": "30720",
         "budget_cpu_year": "120000", "budget_mem_year": "368640"},
        {"department": "技术研发中心-天冕科技-云平台", "budget_cpu_month": "10000", "budget_mem_month": "30720",
         "budget_cpu_year": "120000", "budget_mem_year": "368640"},
        {"department": "技术研发中心-天冕科技-数据平台", "budget_cpu_month": "10000", "budget_mem_month": "30720",
         "budget_cpu_year": "120000", "budget_mem_year": "368640"},
        {"department": "技术研发中心-天冕科技-数据智能", "budget_cpu_month": "10000", "budget_mem_month": "30720",
         "budget_cpu_year": "120000", "budget_mem_year": "368640"},
        {"department": "技术研发中心-天冕科技-人工智能", "budget_cpu_month": "10000", "budget_mem_month": "30720",
         "budget_cpu_year": "120000", "budget_mem_year": "368640"},
        {"department": "技术研发中心-系统运维-运维", "budget_cpu_month": "10000", "budget_mem_month": "30720",
         "budget_cpu_year": "120000", "budget_mem_year": "368640"},
        {"department": "技术研发中心-系统运维-数据库", "budget_cpu_month": "10000", "budget_mem_month": "30720",
         "budget_cpu_year": "120000", "budget_mem_year": "368640"},
    ]

    from common.database import SessionLocal

    session = SessionLocal()
    ContainerQuotaDepartmentBudget.saves(session, container_budget)
    session.close()
